use axum::{extract::{Path, State}, http::StatusCode, response::IntoResponse, Extension, Json};
use chat_core::User;

use crate::{models::CreateChat, AppError, AppState};


pub(crate) async fn list_chat_handler(Extension(user): Extension<User>
,State(state): State<AppState>) -> Result<impl IntoResponse,AppError> {
    let chat = state.fetch_chat_users(user.ws_id as _).await?;
    Ok((StatusCode::OK,Json(chat)).into_response())
}

pub(crate) async fn create_chat_handler(Extension(user): Extension<User>
,State(state): State<AppState>,
Json(input): Json<CreateChat>) -> Result<impl IntoResponse,AppError> {
    let chat = state.create_chat(input,user.ws_id as _).await?;
    Ok((StatusCode::CREATED,Json(chat)).into_response())
}

pub(crate) async fn get_chat_handle(
    State(state): State<AppState>,
    Path(id): Path<i32>
) -> Result<impl IntoResponse,AppError> {
    let chat = state.get_by_id(id as _).await?;
    match chat {
        Some(chat) => Ok(Json(chat)),
        None => Err(AppError::NotFound(format!("Chat with id {} not found", id))),
        
    }
}
pub(crate) async fn update_chat_handler(
    State(state): State<AppState>,
    Path(id): Path<i32>,
    Json(name): Json<String>

) -> Result<impl IntoResponse,AppError> {
    let chat = state.update_chat(id as _, name).await?;
    Ok((StatusCode::OK,Json(chat)).into_response())

}

pub(crate) async fn delete_chat_handler(
    State(state): State<AppState>,
    Path(id): Path<i32>
) -> Result<impl IntoResponse,AppError> {
    let chat = state.delete_by_id(id as _).await?;
    Ok((StatusCode::OK,Json(chat)).into_response())
}
